package com.loyal.mwm.libs.api

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.loyal.mwm.data.ResponseData
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

open class BaseViewModel<T : BaseRepository>(repo: T) : ViewModel() {
    private var viewModelJob: Job? = null
    protected val repository: T = repo

    protected fun <T> viewModelLaunch(
        block: suspend () -> ResponseData<T?>,
        callback: (result: ResponseData<T?>) -> Unit
    ) {
        viewModelJob = viewModelScope.launch { callback.invoke(block.invoke()) }
    }

    fun reload() {
        repository.updateBaseUrl()
    }

    fun cancel() {
        repository.cancelRequest()
        cancelRequestJob()
    }

    private fun cancelRequestJob() {
        if (null == viewModelJob) {
            return
        }
        if (viewModelJob!!.isActive && viewModelJob!!.isCancelled)
            viewModelJob!!.cancel()
    }

    override fun onCleared() {
        super.onCleared()
        cancel()
    }
}